import { memo, useEffect } from "react";
import { connect } from "react-redux";
import { getRankList } from "./store/index";
import { filterIndex } from "../../api/utils";
import { List, ListItem, SongList, Container } from "./style";
import Scroll from "../../baseUI/scroll";
import { EnterLoading } from "../Singers/style";
import Loading from "../../baseUI/loading";
import { renderRoutes  } from "react-router-config";

function Rank(props) {
  console.log(props)
  const { rankList: list, loading } = props;
  const { getRankListDispatch } = props;

  let rankList = list ? list.toJS() : [];

  const enterDetail = (id) => {
    props.history.push(`/rank/${id}`)
  }

  // 渲染榜单列表函数，传入 global 变量来区分不同的布局方式
  const renderRankList = (list, global) => {
    return (
      <List globalRank={global}>
        {
          list.map((item, index) => {
            return (
              <ListItem key={item.id} tracks={item.tracks} onClick={() => enterDetail(item.id)} >
                <div className="img_wrapper">
                  <img src={item.coverImgUrl} alt=""/>
                  <div className="decorate"></div>
                  <span className="update_frequecy">{item.updateFrequency}</span>
                </div>
                {item.tracks.length > 0 && renderSongList(item.tracks)}
              </ListItem>
            )
          })
        }
      </List>
    )
  }

  const renderSongList = (list) => {
    return (
      <SongList>
        {
          list.map((item, index) => {
            return <li key={index}>{index + 1}. {item.first} - {item.second}</li>
          })
        }
      </SongList>
    )
  }

  useEffect(() => {
    getRankListDispatch();
  }, []);

  let globalStartIndex = filterIndex(rankList);
  let officialList = rankList.slice(0, globalStartIndex);
  let globalList = rankList.slice(globalStartIndex);

  let displayStyle = {"display" : loading ? "none" : ""}

  return (
    <Container>
      <Scroll>
        <div>
          <h1 className="offical" style={displayStyle}>官方榜</h1>
          {renderRankList(officialList)}
          <h1 className="global" style={displayStyle}>全球榜</h1>
          {renderRankList(globalList, true)}
          {loading && <EnterLoading><Loading></Loading></EnterLoading>}
        </div>
      </Scroll>
      {renderRoutes(props.route.routes)}
    </Container>
  )
}

const mapStateToProps = (state) => ({
  rankList: state.getIn(["rank", "rankList"]),
  loading: state.getIn(["rank", "loading"]),
});

const mapDispatchToProps = (dispatch) => {
  return {
    getRankListDispatch() {
      dispatch(getRankList());
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(memo(Rank));
